package com.resource.provider.util;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: jim
 * @Date:Create in 17/8/15
 */
public class Https {

    private static Logger logger = Logger.getLogger(Https.class);
    public static String APPID;
    public static String TOKEN;
    public static final String AGURL;
    public static final String SIGNPARAM = "false";

    private static final String OPERATOR_REALNAME;
    private static final String OPERATOR_JOB;
    private static final String OPERATOR_USERNAME;

    /**
     * operatorRealname=org-sys
     operatorJob=org-sys
     operatorUsername=admin
     */

    static {
        APPID = PropsUtil.getNoE("appID");
        TOKEN = PropsUtil.getNoE("token");
        AGURL = PropsUtil.getNoE("agUrl");

        OPERATOR_REALNAME = PropsUtil.getNoE("operatorRealname");
        OPERATOR_JOB = PropsUtil.getNoE("operatorJob");
        OPERATOR_USERNAME = PropsUtil.getNoE("operatorUsername");
    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static JSONObject sendGet(String url, String param) {
        JSONObject jsonObject = null;
        long ts = System.currentTimeMillis() / 1000;
        String sign = Md5Util.md5(APPID + ts + TOKEN + SIGNPARAM).toLowerCase();
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = AGURL + url + "?" + String.format("appID=%s&sign=%s&ts=%s&%s", APPID, sign, ts, param);
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
//            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.out.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.fromObject(result);
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return jsonObject;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendPost(String url, String param) {
        long ts = System.currentTimeMillis() / 1000;
        String sign = Md5Util.md5(APPID + ts + TOKEN + SIGNPARAM).toLowerCase();
        JSONObject jsonObject = null;
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            //适配1.0,2.0 POST接口
//            URL realUrl = new URL(AGURL + url + "?" +
//                    String.format("appID=%s&sign=%s&ts=%s&%s", APPID, sign, ts, param));
            URL realUrl = new URL(AGURL + url);
            System.out.println("地址：" + realUrl);
            //System.out.println("realUrl:"+realUrl);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(String.format("appID=%s&sign=%s&ts=%s&%s", APPID, sign, ts, param));
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            jsonObject = JSONObject.fromObject(result);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return jsonObject;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static JSONObject sendPostForPerson(String url, String param) {
        param += "&operatorRealname=" + OPERATOR_REALNAME + "&operatorJob=" +
                OPERATOR_JOB + "&operatorUsername=" + OPERATOR_USERNAME;
        long ts = System.currentTimeMillis() / 1000;
        String sign = Md5Util.md5(APPID + ts + TOKEN + SIGNPARAM).toLowerCase();
        JSONObject jsonObject = new JSONObject();
        try {
            String result = requestPostCase(AGURL + url, String.format("appID=%s&sign=%s&ts=%s&%s", APPID, sign, ts, param));
            jsonObject = JSONObject.fromObject(result);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        return jsonObject;
    }

    public static String requestPostCase(String url, String json) throws ConnectException {
        String result = "";//缓存请求数据
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            //System.out.println("post-url:" + url + "\n" + json);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
//			 设置 HttpURLConnection的字符编码
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStream out = conn.getOutputStream();
            out.write(json.getBytes("utf-8"));
            // flush输出流的缓冲
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (ConnectException e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static String requestPostCase(String url, String json, JSONObject header) {
        String result = "";//缓存请求数据
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            Iterator<String> keys = header.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                conn.setRequestProperty(key, header.getString(key));
            }
            conn.setDoOutput(true);
            conn.setDoInput(true);
            OutputStream out = conn.getOutputStream();
            out.write(json.getBytes("utf-8"));
            // flush输出流的缓冲
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);

            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送PUT请求。
     *
     * @param urlPath url地址。
     * @param data    参数。
     * @param header
     */
    public static String sendPut(String urlPath, String data, String[] header) {
        long ts = System.currentTimeMillis() / 1000;
        String sign = Md5Util.md5(APPID + ts + TOKEN + SIGNPARAM).toLowerCase();
        String result = null;
        URL url = null;
        HttpURLConnection httpurlconnection = null;
        try {
            url = new URL(AGURL + urlPath);
            httpurlconnection = (HttpURLConnection) url.openConnection();
            httpurlconnection.setDoInput(true);
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setConnectTimeout(2000000);// 设置连接主机超时（单位：毫秒）
            httpurlconnection.setReadTimeout(2000000);// 设置从主机读取数据超时（单位：毫秒）

            if (header != null) {
                for (int i = 0; i < header.length; i++) {
                    String[] content = header[i].split(":");
                    httpurlconnection.setRequestProperty(content[0], content[1]);
                }
            }

            httpurlconnection.setRequestMethod("PUT");
            httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            if (StringUtils.isNotBlank(data)) {
                data = String.format("appID=%s&sign=%s&ts=%s&%s", APPID, sign, ts, data);
                httpurlconnection.getOutputStream().write(data.getBytes("UTF-8"));
            }
            httpurlconnection.getOutputStream().flush();
            httpurlconnection.getOutputStream().close();
            int code = httpurlconnection.getResponseCode();

            if (code == 200) {
                DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
                int len = in.available();
                byte[] by = new byte[len];
                in.readFully(by);
                result = new String(by, Charset.forName("UTF-8"));
                in.close();
            } else {
                logger.error("请求地址：" + urlPath + "返回状态异常，异常号为：" + code);
            }
        } catch (Exception e) {
            logger.error("访问url地址：" + urlPath + "发生异常", e);
        } finally {
            url = null;
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
        }
        return result;
    }

    public static String sendDelete(String urlPath) {
        String result = null;
        URL url = null;
        HttpURLConnection httpurlconnection = null;
        try {
            url = new URL(urlPath);
            httpurlconnection = (HttpURLConnection) url.openConnection();
            httpurlconnection.setDoInput(true);
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setConnectTimeout(2000000);// 设置连接主机超时（单位：毫秒）
            httpurlconnection.setReadTimeout(2000000);// 设置从主机读取数据超时（单位：毫秒）


            httpurlconnection.setRequestMethod("DELETE");
            httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            httpurlconnection.getOutputStream().flush();
            httpurlconnection.getOutputStream().close();
            int code = httpurlconnection.getResponseCode();

            if (code == 200) {
                DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
                int len = in.available();
                byte[] by = new byte[len];
                in.readFully(by);
                result = new String(by, Charset.forName("UTF-8"));
                in.close();
            } else {
                logger.error("请求地址：" + urlPath + "返回状态异常，异常号为：" + code);
            }
        } catch (Exception e) {
            logger.error("访问url地址：" + urlPath + "发生异常", e);
        } finally {
            url = null;
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
        }
        return result;
    }

}
